import { EncodeRulesService } from './../../../../@core/services/encoderRule/encode-rules.service';
import { SupplierService } from './../../../../@core/services/supplier/supplier.service';
import cityData from 'src/app/@core/mock/city.json';
import { Supply } from './../../../../@core/data/supplier';
import { Component } from '@angular/core';
import { CascaderItem, DialogService, DValidateRules, FormLayout, TableWidthConfig } from 'ng-devui';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { Router } from '@angular/router';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { AddLinkManComponent } from '../../customer/add-customer/add-link-man/add-link-man.component';
@Component({
  selector: 'app-supplier-add',
  templateUrl: './supplier-add.component.html',
  styleUrls: ['./supplier-add.component.scss']
})
export class SupplierAddComponent {
  layoutDirection: FormLayout = FormLayout.Horizontal;
  tabActiveId: string | number = '基本信息';
  supplier: Supply = {
    supplyId: null,
    supplyNum: '',
    supplyShortName: '',
    supplyChineseName: '',
    supplyEnglishName: '',
    supplyAccount: '',
    supplyPassword: '',
    supplySupplyClassId: 0,
    supplyClassName: '',
    salesmanId: 0,
    salesmanName: '',
    country: '中国',
    province: '',
    city: '',
    district: '',
    address: '',
    phone: '',
    fax: '',
    email: '',
    contactPerson: '',
    isInvoicing: false,
    taxRate: 0,
    supplyCollectionPeriodId: null,
    collectionPeriodName: '',
    supplySettlementMethodId: null,
    settlementMethodName: '',
    supplyCurrencyId: null,
    currencyName: '',
    file: '',
    isEnable: false,
    createDate: null,
    supplyContacts: [],
  }
  supplierRules: { [key: string]: DValidateRules } = {
    supplyNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*供应商编码不能为空' },
        { minlength: 2, message: '*供应商编码长度至少为2' },
        { maxlength: 40, message: '*供应商编码长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*供应商编码不能包含空格' }
      ]
    },
    supplierAbbreviation: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*供应商简称不能为空' }
      ]
    },
    chineseName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*供应商中文全名不能为空' }
      ]
    },
    supplierClassId: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*供应商类别不能为空' }
      ]
    },
    salesmanName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*业务员不能为空' }
      ]
    },
  }
  msgs: { severity: any; summary: any; content: any; }[];
  city = []
  supplierClassId = [];
  supplierCategorys: any[] = []
  currencyOptions: any[] = []
  settlementMethodOptions: any[] = []
  settlementMethodDefault: any = {}
  collectionPeriodsOptions: any[] = []
  collectionPeriodDefault: any = {}
  currencyDefault: any = {}
  address: any = [
    this.supplier.province, this.supplier.city, this.supplier.district
  ]
  taxRate: any = 0
  fujianNumber: any = 0
  tableData=[]
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'caozuo',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
  ];//表格宽度配置
  constructor(private SupplierService: SupplierService, private DialogService: DialogService, private CustomerService: CustomerService,private Router:Router,private EncodeRulesService:EncodeRulesService) {
    this.city = cityData;
  }
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule('供应商编码','供应商编码').subscribe((res:any)=>{
      this.supplier.supplyNum = res
    })
    this.SupplierService.getSupplierClass().subscribe((res: any) => {
      this.supplierCategorys = this.convertToCascaderItem(res)
    })
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((res: any) => {
      this.currencyOptions = res.items
      this.currencyDefault = this.currencyOptions.find(item => item.isDefault == true)
      this.supplier.currencyName = this.currencyDefault.currencyName
      this.supplier.supplyCurrencyId = this.currencyDefault.currencyId
    })
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe((res: any) => {
      this.settlementMethodOptions = res.items
      this.settlementMethodDefault = this.settlementMethodOptions.find(item => item.isDefault == true)
      this.supplier.settlementMethodName = this.settlementMethodDefault.settlementMethodName
      this.supplier.supplySettlementMethodId = this.settlementMethodDefault.settlementMethodId
    })
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '付款'
    }).subscribe((res: any) => {
      this.collectionPeriodsOptions = res.items
      this.collectionPeriodDefault = this.collectionPeriodsOptions.find(item => item.isDefault == true)
    })
  }
  submit($event: any) {
    if($event.valid){
      this.supplier.createDate = new Date()
      this.SupplierService.addSupplier(this.supplier).subscribe((res: any) => {
          this.showToast('success', '提示', '添加成功')
          setTimeout(() => {
            this.Router.navigate(['/pages/basicdata/supplier'])
          }, 1000);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    )
    }
  }
  supplierClassChange($event: any) {
    this.supplier.supplySupplyClassId = $event[$event.length - 1]
    this.supplier.supplyClassName = this.findLabelById(this.supplierCategorys, this.supplier.supplySupplyClassId)
  }
  salesmanChange(dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择业务员',
      content: SelectUserComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.supplier.salesmanName = results.modalContentInstance.selectData.name;
            this.supplier.salesmanId = results.modalContentInstance.selectData.id;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  currencyOptionsChange($event: any) {
    this.supplier.currencyName = $event.currencyName
    this.supplier.supplyCurrencyId = $event.currencyId
  }
  cityChange() {
    this.supplier.province = this.address[0]
    this.supplier.city = this.address[1]
    this.supplier.district = this.address[2]
  }
  taxRateChange() {
    this.supplier.taxRate = this.taxRate / 100
  }
  CollectionPeriodChange($event: any) {
    this.supplier.collectionPeriodName = $event.collectionPeriodName
    this.supplier.supplyCollectionPeriodId = $event.collectionPeriodId
  }
  settlementMethodsChange($event: any) {
    this.supplier.settlementMethodName = $event.settlementMethodName
    this.supplier.supplySettlementMethodId = $event.settlementMethodId
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '供应商附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '物料附件',
        urls: this.supplier.file
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.supplier.file = results.modalContentInstance.urls;
            this.fujianNumber = this.supplier.file.split(',').length
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cancle() {
    this.Router.navigate(['/pages/basicdata/supplier'])
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  convertToCascaderItem(data: any[]): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.supplyClassName,
        value: item.supplyClassId,
      };
      if (item.subSupplyClasses) {
        cascaderItem.children = this.convertToCascaderItem(item.subSupplyClasses);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  findLabelById(categories: any, value: number): string | undefined {
    for (const category of categories) {
      if (category.value === value) {
        return category.label;
      }
      if (category.children) {
        const foundLabel = this.findLabelById(category.children, value);
        if (foundLabel) {
          return foundLabel;
        }
      }
    }
    return undefined; // 如果没有找到匹配的id，返回undefined
  }
  addLinkMan(dialogtype?: string) {
    let data = {
      display: false,
      name:'供应商'
    };
    const results = this.DialogService.open({
      id: '添加联系人',
      width:'450px',
      title: '添加联系人',
      data: data,
      content: AddLinkManComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.supplierLinkMan.supplyContactName) {
              if(results.modalContentInstance.supplierLinkMan.isDefault){
                this.tableData.forEach(item=>{
                  item.isDefault = false
                })
              }
              this.tableData.push(results.modalContentInstance.supplierLinkMan)
              this.supplier.supplyContacts = this.tableData
              results.modalInstance.hide();
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  editLinkMan(rowItem: any, i: any, dialogtype?: string) {
    let data = {
      display: false,
      rowItem: rowItem,
      name:'供应商'
    };
    const results = this.DialogService.open({
      id: '编辑联系人',
      width:'450px',
      title: '编辑联系人',
      data: data,
      content: AddLinkManComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.supplierLinkMan.supplyContactName) {
              if(results.modalContentInstance.supplierLinkMan.isDefault){
                this.tableData.forEach(item=>{
                  item.isDefault = false
                })
              }
              this.tableData[i] = results.modalContentInstance.supplierLinkMan;
              this.supplier.supplyContacts = this.tableData
              results.modalInstance.hide();
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  remove(i: number) {
    this.tableData.splice(i, 1);
  }//删除人员
}
